package com.sixmac.util;

import com.alibaba.fastjson.JSONObject;
import com.sixmac.common.constant.TempConstant;
import com.sixmac.core.plugins.dao.Blade;
import com.sixmac.core.toolbox.ajax.AjaxResult;
import com.sixmac.core.toolbox.kit.DateKit;
import com.sixmac.core.toolbox.kit.JsonKit;
import com.sixmac.module.*;
import com.sixmac.utils.HttpRequestUtil;
import org.apache.poi.ss.formula.functions.T;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.Date;

/**
 * Created by admin on 2018/8/31.
 */

public class Push{


    public void sendSucess(Contract contract,WeChatConfig weChatConfig) {
        Tenant tenant = Blade.create(Tenant.class).findById(contract.getTentantId());
        AccessToken accessToken = Blade.create(AccessToken.class).findFirstBy("",null);
        if (accessToken!=null&&(System.currentTimeMillis() - accessToken.getCreatTime().getTime()) / (1000 * 60)>=60){
            Blade.create(AccessToken.class).delete(accessToken.getId());
            accessToken = null;
        }
        if (accessToken == null){
            String wxspAppid = weChatConfig.getAppId();
            String wxspSecret = weChatConfig.getSecret();
            String sr = HttpRequestUtil.sendGet("https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid="+wxspAppid+"&secret="+wxspSecret, null);
            JSONObject json = JsonKit.parse(sr);
            //获取会话密钥（session_key）
            //  String session_key = json.get("session_key").toString();
            //用户的唯一标识（openid）
            if (json.containsKey("access_token")){
                String access_token = (String) json.get("access_token");
                accessToken = new AccessToken();
                accessToken.setCreatTime(new Date());
                accessToken.setToken(access_token);
                Blade.create(AccessToken.class).save(accessToken);
            }
        }

        Room room = Blade.create(Room.class).findById(contract.getRoomId());
        AccessFrom form = Blade.create(AccessFrom.class).findFirstBy("isUse = 0 and userId="+tenant.getId()+" and type = 1 ",null);
        /**
         * 入住人
         {{keyword1.DATA}}
         入住房间
         {{keyword3.DATA}}
         离店日期
         {{keyword4.DATA}}
         入住日期
         {{keyword5.DATA}}
         */
        if(form != null){
            JSONObject object = new JSONObject();
            object.put("touser",tenant.getWechatKey());
            object.put("template_id", TempConstant.CHECK_TEMP_YES);
            object.put("page","/index/index");
            object.put("form_id",form.getFormId());
            JSONObject data = new JSONObject();
            JSONObject keyword1 = new JSONObject();
            keyword1.put("value",tenant.getName());
            JSONObject keyword2 = new JSONObject();
            keyword2.put("value",room.getAddress()+" "+room.getRoomNo());
            JSONObject keyword3 = new JSONObject();
            keyword3.put("value", DateKit.getTime(contract.getStartTime()));
            JSONObject keyword4 = new JSONObject();
            keyword4.put("value",DateKit.getTime(contract.getEndTime()));
            data.put("keyword1",keyword1);
            data.put("keyword2",keyword2);
            data.put("keyword3",keyword3);
            data.put("keyword4",keyword4);
            object.put("data",data);

            String result = HttpRequestUtil.sendPost(" https://api.weixin.qq.com/cgi-bin/message/wxopen/template/send?access_token="+accessToken.getToken(),object.toJSONString());
            System.out.println(result);

            //发送短信

            form.setIsUse(1);
            Blade.create(AccessFrom.class).update(form);
        }
        TenantRoom tenantRoom = Blade.create(TenantRoom.class).findById(contract.getTenantRoomId());
        tenantRoom.setStatus(1);
        tenantRoom.setApprove(1);
        Blade.create(TenantRoom.class).update(tenantRoom);
    }


    /**
     * 拒绝模板
     * @param tenant
     */
    public void sendError(Tenant tenant,String info,WeChatConfig weChatConfig) {

        AccessToken accessToken = Blade.create(AccessToken.class).findFirstBy("",null);
        if (accessToken!=null&&(System.currentTimeMillis() - accessToken.getCreatTime().getTime()) / (1000 * 60)>=60){
            Blade.create(AccessToken.class).delete(accessToken.getId());
            accessToken = null;
        }
        if (accessToken == null){
            String wxspAppid = weChatConfig.getAppId();
            String wxspSecret = weChatConfig.getSecret();
            String sr = HttpRequestUtil.sendGet("https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid="+wxspAppid+"&secret="+wxspSecret, null);
            JSONObject json = JsonKit.parse(sr);
            //获取会话密钥（session_key）
            //  String session_key = json.get("session_key").toString();
            //用户的唯一标识（openid）
            if (json.containsKey("access_token")){
                String access_token = (String) json.get("access_token");
                accessToken = new AccessToken();
                accessToken.setCreatTime(new Date());
                accessToken.setToken(access_token);
                Blade.create(AccessToken.class).save(accessToken);
            }
        }

        TenantRoom tenantRoom = Blade.create(TenantRoom.class).findFirstBy(" tenantId="+tenant.getId()+" and approve=3 ",null);
        Landlord landlord = Blade.create(Landlord.class).findById(tenantRoom.getLandlordId());

        Room room = Blade.create(Room.class).findById(tenantRoom.getRoomId());

        /**
         * 酒店名称
         {{keyword1.DATA}}
         拒绝原因
         {{keyword2.DATA}}
         客服电话
         {{keyword3.DATA}}
         */
        AccessFrom form = Blade.create(AccessFrom.class).findFirstBy("isUse = 0 and userId="+tenant.getId()+" and type = 1 ",null);
        if(form != null){
            JSONObject object = new JSONObject();
            object.put("touser",tenant.getWechatKey());
            object.put("template_id", TempConstant.CHECK_TEMP_NO);
            object.put("page","/index/index");
            object.put("form_id",form.getFormId());
            JSONObject data = new JSONObject();
            JSONObject keyword1 = new JSONObject();
            keyword1.put("value",room.getAddress()+" "+room.getRoomNo());
            JSONObject keyword2 = new JSONObject();
            keyword2.put("value",info);
            JSONObject keyword3 = new JSONObject();
            keyword3.put("value",landlord.getMobile());
            data.put("keyword1",keyword1);
            data.put("keyword2",keyword2);
            data.put("keyword3",keyword3);
            object.put("data",data);

            String result = HttpRequestUtil.sendPost(" https://api.weixin.qq.com/cgi-bin/message/wxopen/template/send?access_token="+accessToken.getToken(),object.toJSONString());
            System.out.println(result);

            //发送短信

            form.setIsUse(1);
            Blade.create(AccessFrom.class).update(form);
        }
        tenantRoom.setStatus(1);
        tenantRoom.setApprove(1);
        Blade.create(TenantRoom.class).update(tenantRoom);
    }

    /**
     * 拒绝模板
     * @param contract
     */
    public void sendOut(Contract contract,WeChatConfig weChatConfig) {

        Tenant tenant = Blade.create(Tenant.class).findById(contract.getTentantId());

        AccessToken accessToken = Blade.create(AccessToken.class).findFirstBy("",null);
        if (accessToken!=null&&(System.currentTimeMillis() - accessToken.getCreatTime().getTime()) / (1000 * 60)>=60){
            Blade.create(AccessToken.class).delete(accessToken.getId());
            accessToken = null;
        }
        if (accessToken == null){
            String wxspAppid = weChatConfig.getAppId();
            String wxspSecret = weChatConfig.getSecret();
            String sr = HttpRequestUtil.sendGet("https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid="+wxspAppid+"&secret="+wxspSecret, null);
            JSONObject json = JsonKit.parse(sr);
            //获取会话密钥（session_key）
            //  String session_key = json.get("session_key").toString();
            //用户的唯一标识（openid）
            if (json.containsKey("access_token")){
                String access_token = (String) json.get("access_token");
                accessToken = new AccessToken();
                accessToken.setCreatTime(new Date());
                accessToken.setToken(access_token);
                Blade.create(AccessToken.class).save(accessToken);
            }
        }

        TenantRoom tenantRoom = Blade.create(TenantRoom.class).findFirstBy(" tenantId="+tenant.getId()+" and status = 1  and approve=1 ",null);

        Room room = Blade.create(Room.class).findById(tenantRoom.getRoomId());

        /**
         房间号码
         {{keyword2.DATA}}
         入住人
         {{keyword3.DATA}}
         预订手机
         {{keyword4.DATA}}
         入住时间
         {{keyword5.DATA}}
         退房时间
         {{keyword6.DATA}}
         */
        AccessFrom form = Blade.create(AccessFrom.class).findFirstBy("isUse = 0 and userId="+tenant.getId()+" and type = 1 ",null);
        if(form != null){
            JSONObject object = new JSONObject();
            object.put("touser",tenant.getWechatKey());
            object.put("template_id", TempConstant.CHECK_TEMP_OUT);
            object.put("page","/index/index");
            object.put("form_id",form.getFormId());
            JSONObject data = new JSONObject();
            JSONObject keyword1 = new JSONObject();
            keyword1.put("value",room.getRoomNo());
            JSONObject keyword2 = new JSONObject();
            keyword2.put("value",tenant.getName());
            JSONObject keyword3 = new JSONObject();
            keyword3.put("value",tenant.getMobile());
            JSONObject keyword4 = new JSONObject();
            keyword4.put("value",tenantRoom.getStartDate());
            JSONObject keyword5 = new JSONObject();
            keyword5.put("value",tenantRoom.getEndDate());
            data.put("keyword1",keyword1);
            data.put("keyword2",keyword2);
            data.put("keyword3",keyword3);
            data.put("keyword4",keyword4);
            data.put("keyword5",keyword5);
            object.put("data",data);

            String result = HttpRequestUtil.sendPost(" https://api.weixin.qq.com/cgi-bin/message/wxopen/template/send?access_token="+accessToken.getToken(),object.toJSONString());
            System.out.println(result);

            //发送短信

            form.setIsUse(1);
            Blade.create(AccessFrom.class).update(form);
        }
        tenantRoom.setStatus(2);
        tenantRoom.setApprove(2);
        Blade.create(TenantRoom.class).update(tenantRoom);
    }

    /**
     * 开锁通知
     * @param tenant
     * @param landlord
     */
    public void openClock(Tenant tenant,Landlord landlord,Integer roomId,WeChatConfig weChatConfig) {

        AccessToken accessToken = Blade.create(AccessToken.class).findFirstBy("",null);
        if (accessToken!=null&&(System.currentTimeMillis() - accessToken.getCreatTime().getTime()) / (1000 * 60)>=60){
            Blade.create(AccessToken.class).delete(accessToken.getId());
            accessToken = null;
        }
        if (accessToken == null){
            String wxspAppid = weChatConfig.getAppId();
            String wxspSecret = weChatConfig.getSecret();
            String sr = HttpRequestUtil.sendGet("https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid="+wxspAppid+"&secret="+wxspSecret, null);
            JSONObject json = JsonKit.parse(sr);
            //获取会话密钥（session_key）
            //  String session_key = json.get("session_key").toString();
            //用户的唯一标识（openid）
            if (json.containsKey("access_token")){
                String access_token = (String) json.get("access_token");
                accessToken = new AccessToken();
                accessToken.setCreatTime(new Date());
                accessToken.setToken(access_token);
                Blade.create(AccessToken.class).save(accessToken);
            }
        }


        Room room = Blade.create(Room.class).findById(roomId);

        /**
         * 开锁时间
         {{keyword1.DATA}}
         开锁者
         {{keyword2.DATA}}
         位置
         {{keyword3.DATA}}
         备注
         {{keyword4.DATA}}
         */
        AccessFrom form = null;
        if (tenant!=null)
            form = Blade.create(AccessFrom.class).findFirstBy("isUse = 0 and userId="+tenant.getId()+" and type = 1 ",null);
        if (landlord!=null)
            form = Blade.create(AccessFrom.class).findFirstBy("isUse = 0 and userId="+landlord.getId()+" and type = 2 ",null);
        if(form != null){
            JSONObject object = new JSONObject();
            object.put("touser",tenant!=null?tenant.getWechatKey():landlord.getWechatKey());
            object.put("template_id", TempConstant.OPEN_LOCK);
            object.put("page","/index/index");
            object.put("form_id",form.getFormId());
            JSONObject data = new JSONObject();
            JSONObject keyword1 = new JSONObject();
            keyword1.put("value",new Date());
            JSONObject keyword2 = new JSONObject();
            keyword2.put("value",tenant!=null?tenant.getName():landlord.getName());
            JSONObject keyword3 = new JSONObject();
            keyword3.put("value",room.getAddress());
            JSONObject keyword4 = new JSONObject();
            keyword4.put("value","锁已打开，可以进入房间。");
            data.put("keyword1",keyword1);
            data.put("keyword2",keyword2);
            data.put("keyword3",keyword3);
            data.put("keyword4",keyword4);
            object.put("data",data);

            String result = HttpRequestUtil.sendPost(" https://api.weixin.qq.com/cgi-bin/message/wxopen/template/send?access_token="+accessToken.getToken(),object.toJSONString());
            System.out.println(result);

            //发送短信

            form.setIsUse(1);
            Blade.create(AccessFrom.class).update(form);
        }
    }
}
